#include "net/Acceptor.h"
#include "net/EventLoop.h"
#include "Base/Logger.h"

namespace toym
{
namespace net
{

///////////////////////////////////////////////
/////    Public functions
////////////////////////////////////////////////
Acceptor::Acceptor(EventLoop* loop, const InetAddress& addr)
    : m_loop(loop),
      m_acceptSocket(Socket::createSocket()),
      m_channel(m_acceptSocket.getFd(), loop),
      m_newConnectionCb()
{
    if(m_acceptSocket.setReuse(true) < 0)
        ::abort();
    if (m_acceptSocket.bind(addr) < 0) 
        ::abort();
    m_channel.setReadCallback([this](){
        this->handleRead();
    });
    m_channel.setErrorCallback([this]() {
        this->handleError();
    });
}

void Acceptor::listen() {
    if (m_acceptSocket.listen(100) < 0) 
        ::abort();
    m_channel.enbaleRead();
}

///////////////////////////////////////////////
/////    Public functions
////////////////////////////////////////////////
void Acceptor::handleRead() {
    InetAddress peerAddr(0);
    int sockfd = m_acceptSocket.accept(peerAddr);
    if (sockfd < 0) {
        LOG_ERROR << "new Connection Error";
        return ;
    }
    Socket sock(sockfd);
    if (m_newConnectionCb) {
        m_newConnectionCb(std::move(sock), peerAddr);
    }
    // 没有就自动析构
    // 会关闭连接
}

void Acceptor::handleError() {
    LOG_ERROR << "Acceptor::handleError error";
}


} // namespace net

} // namespace toym
